package com.lanyou.esb.redis.proxy.base;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.Jedis;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.redis.JedisPoolUtils;
import com.lanyou.esb.redis.proxy.StrJedisProxy;

/**
 * String数据类型,操作Redis基础代理类
 * 
 * @author Davey.wu
 */
public abstract class BaseStrJedisProxy<T> extends BaseJedisProxy<T> implements
		StrJedisProxy<T> {
	protected static final String STRING_SET_RESULT = "OK";

	private int timeOut;
	private String prefix;

	@Override
	public T get(String key) throws JsonParseException, JsonMappingException,
			IOException {
		String value = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return null;
		}
		boolean broken = false;
		try {
			value = jedis.get(key);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (StringUtils.isBlank(value)) {
			return null;
		}
		return fromJson(value);
	}

	@Override
	public void loadAll() throws JsonProcessingException {
	}

	@Override
	public long setex(String key, T target) throws JsonProcessingException {
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			result = jedis.setex(key, timeOut, toJson(target));
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (StringUtils.isBlank(result)) {
			return 0l;
		}
		if (STRING_SET_RESULT.equalsIgnoreCase(result)) {
			return 1;
		}
		return 0l;
	}

	public int getTimeOut() {
		return timeOut;
	}

	public void setTimeOut(int timeOut) {
		this.timeOut = timeOut;
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
}
